<?php

// 新增投资机构
// POST organization.add

namespace app\api\resource\organization;
use think\Db;
use think\Loader;

class Add
{
    // 方法
    public $_method = ['POST'];
    // 前置
    public $_pre    = [];
    // 描述
    public $_description = '新增投资机构';
    // 参数
    public $_param  = [
        'title'        => '投资机构名称',
        'logo'         => '投资机构LOGO',
        'introduction' => '投资机构简介',
    ];
    // 返回
    public $_return = [
        201 => '新增成功',
        400 => '该投资机构已存在',
        422 => '请求参数不合法',
        500 => '服务器错误',
    ];

    public function run(&$request)
    {
        $params['title']        = $request->post('title/s', '', 'trim');
        $params['logo']         = $request->post('logo/s', '', 'trim');
        $params['introduction'] = $request->post('introduction/s', '', 'trim');

        $validate = Loader::validate('Organization');
        if ( !$validate->scene('add')->check($params) ) {
            $errMsg = $validate->getError();
            return [422,$errMsg];
        }

        $ret = Db::name('organization')->where('title',$params['title'])->find();
        if ( !is_null($ret) ) return [400,'该投资机构已存在'];

        $data['title']        = $params['title'];
        $data['logo']         = $params['logo'];
        $data['introduction'] = $params['introduction'];
        $data['status']       = 1;
        $num = Db::name('organization')->insert($data);
        return ($num > 0) ? [201,$data] : 500;
    }
}